// 上传照片列表
<template>
    <div class="picList">
        <v-accordion :title="title" class="infoList" :opened="opened">
            <div slot="title">
                <span v-if="$slots.title"><slot name="title"></slot></span>
                <span v-else>{{title}} <span style="color:#1990FF;font-weight:400">（{{count}}）</span> </span>
            </div>
            <template v-if="sectionList.length>0">
                <!-- opened值：如果active为0，则代表双确认项已全部确认完毕，则全部展开，否则展开双确认项 -->
                <v-accordion
                    v-for="(pitem,pindex) in sectionList"
                    :key="pindex"
                    :title="`第${chineseIndex[pitem.groupNum-1]}阶段`" 
                    class="infoList" 
                    :showSolid="false"
                    :opened="active==0||isOffline?true:active==pindex+1"
                >
                    <section slot="accordion-title-right" v-if="pitem.confirmInfo&&pitem.confirmInfo.overtimeEntity&&pitem.confirmInfo.overtimeEntity.id">
                        <span class="tag tag-yellow-fill" @click="handleOverTime(pitem.confirmInfo.overtimeEntity)" v-if="pitem.confirmInfo.overtimeEntity.pstatus==7">超期已处理</span>
                        <span class="tag tag-red-fill" @click="handleOverTime(pitem.confirmInfo.overtimeEntity)" v-else>超期未处理</span>
                    </section>
                    <f7-list media-list class="search-list" v-if="pitem.fileList.length > 0">
                        <li
                            v-for="(item, index) in pitem.fileList"
                            :key="index"
                            class="content-box"
                        >
                            <div class="index-box">{{ index + 1 }}</div>
                            <div class="right-box">
                                <div
                                    class="right-box-top"
                                    :class="item.allowNone == 1 ? 'checks-box' : ''"
                                >
                                    <div class="code">
                                        <section>
                                            <span
                                                style="color: #f15a5a; margin-right: 2px"
                                                v-if="item.isMustUpload"
                                            >*</span>
                                            {{ item[props.name] }}
                                            <span v-if="disabled&&item.attachments.length==0" class="noUpload">未上传</span>
                                        </section>
                                        <div v-if="$slots.nameRight"><slot name="nameRight"></slot></div>
                                    </div>
                                    <van-checkbox
                                        v-if="item.allowNone == 1&&!disabled"
                                        v-model="item.isNil"
                                        shape="square"
                                        @click="checkItem(item,index)"
                                        >无此项</van-checkbox
                                    >
                                </div>
                                <div class="right-box-bottom">
                                    <qm-file-upload
                                        :ref="`${listName}${index + 1}${pindex}`"
                                        :galleryOptions="{ multiple: true, maximum: 9 }"
                                        isDefaultFile
                                        :defaultFiles="item.attachments"
                                        :disabled="disabled||(item.isConfirm==1&&(active>(pindex+1)||active==0))"
                                        :extensions="extensions"
                                        :accept="accept"
                                        :actionsOneGroup="actionsGroup(item)"
                                        :maximagescount="maximagescount"
                                        :showLegend="{show:item.templateAttachs!=null&&item.templateAttachs.length,id:item.templateAttachs!=null&&item.templateAttachs.length ? item.templateAttachs[0].attachmentId : ''}"
                                        :params="{
                                            type: 'attach',
                                            dataKey: dataKey,
                                            bizType: item.bizType,
                                            typeCode,
                                            address
                                        }"
                                        :showOffline="isOffline==1"
                                        @onSuccess="fileOnSuccess"
                                        @deleteFileAfter="deleteFileAfter"
                                        :uploadId="`${listName}${index + 1}${pindex}`"
                                    >
                                    </qm-file-upload>
                                </div>
                            </div>
                        </li>
                        <ul class="confirm-ul" v-if="pitem.confirmInfo">
                            <li 
                                class="confirm-li" 
                                @click="confirmModel.isInsOrg&&confirmModel.showConfirmBtn?handleConfirm(pitem,'1',pindex,'insStatus'):noPermission('install')"
                            >
                                <span v-if="pitem.confirmInfo.insStatus">{{pitem.confirmInfo.insUserName}}</span>
                                <span v-else class="toSure">{{confirmModel.pstatus!=7?'待':'未'}}确认</span>
                                <span>安装单位</span>
                                <template v-if="pitem.confirmInfo.insIsTimeout">
                                    <!-- <span v-if="pitem.confirmInfo.insStatus" style="color:#3385FF;margin-top: 5px;" @click="handleOverTime(pitem.confirmInfo.overtimeEntity)">处理情况></span> -->
                                    <img v-if="!pitem.confirmInfo.insStatus" src="../../../../assets/img/qzjx/overNotSure.svg" alt="">
                                    <img v-else src="../../../../assets/img/qzjx/overSure.svg" alt="">
                                </template>
                                <img v-if="!pitem.confirmInfo.insIsTimeout&&pitem.confirmInfo.insStatus" src="../../../../assets/img/qzjx/sure.png" alt="">
                            </li>
                            <li 
                                class="confirm-li" 
                                @click="confirmModel.isConOrg&&confirmModel.showConfirmBtn?handleConfirm(pitem,'1',pindex,'conStatus'):noPermission('construction')"
                            >
                                <span v-if="pitem.confirmInfo.conStatus">{{pitem.confirmInfo.conUserName}}</span>
                                <span v-else class="toSure">{{confirmModel.pstatus!=7?'待':'未'}}确认</span>
                                <span>施工单位</span>
                                <template v-if="pitem.confirmInfo.conIsTimeout">
                                    <!-- <span v-if="pitem.confirmInfo.conStatus" style="color:#3385FF;margin-top: 5px;" @click="handleOverTime(pitem.confirmInfo.overtimeEntity)">处理情况></span> -->
                                    <img v-if="!pitem.confirmInfo.conStatus" src="../../../../assets/img/qzjx/overNotSure.svg" alt="">
                                    <img v-else src="../../../../assets/img/qzjx/overSure.svg" alt="">
                                </template>
                                <img v-if="!pitem.confirmInfo.conIsTimeout&&pitem.confirmInfo.conStatus" src="../../../../assets/img/qzjx/sure.png" alt="">
                            </li>
                        </ul>
                        <van-notice-bar v-if="active==pindex+1" color="#FD5050" background="#FFF3F3" left-icon="info-o" wrapable :scrollable="false">
                            此模块由【拆卸单位专业技术人员，施工单位专职机管员】填写，其它用户无需操作
                        </van-notice-bar>
                    </f7-list>
                </v-accordion>
            </template>
        </v-accordion>
    </div>
</template>

<script>
import Config from '@/libs/config.js'
export default {
    name: 'v-picture-list',
    props: {
        listName: {
            type: String,
        },
        title: {
            type: String,
        },
        typeCode: {
            type: String,
            require: true,
        },
        props: {
            type: Object,
            default: () => {
                return { name: 'name' }
            },
        },
        // 附件主键
        dataKey: {
            type: String,
            require: true,
        },
        attachCraneType: {
            type: String,
            default: '',
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        extensions: {
            type: String,
            default: 'jpg,jpeg,png',
        },
        accept: {
            type: String,
            default: '.jpg,.jpeg,.png',
        },
        opened: {
            type: Boolean,
            default: true,
        },
        address: {
            type: String,
            default: '',
        },
        // 上传方式的选择 1相册 2拍照 3文件
        actionsOneGroup: {
            type: Array,
            default: () => {
                return [1]
            },
        },
        maximagescount: {
            type: Number,
            default: 0
        },
        confirmModel:{
            type:Object,
            default:()=>({showConfirmBtn:false})
        }
    },
    data() {
        return {
            download: Config.api.download,
            isOffline:false,
            list: [],
            unwacth: null,
            count:'0/0',
            sectionList:[
                // {
                //     name:'第一步',
                //     code:1,
                //     confirmInfo:{
                //         insStatus:0,
                //         conStatus:0,
                //     },
                //     fileList:[
                //         {
                //             isConfirm:true,
                //             allowMark: 1,
                //             allowNone: 0,
                //             attachReserved1: null,
                //             attachReserved2: null,
                //             attachReserved3: null,
                //             attachmentId: null,
                //             attachments: [],
                //             bizType: "SENCE_INSTALL_0_0_0_1",
                //             children: [],
                //             craneType: null,
                //             customDesc: "辅助汽车吊检测报告",
                //             customName: "辅助汽车吊检测报告",
                //             dataKey: null,
                //             fileName: null,
                //             fileSizeLimit: null,
                //             fileType: null,
                //             fileTypes: null,
                //             id: "0fdb3db6-139f-4839-b50d-fbc6b7c112f9",
                //             isConfirm: null,
                //             isEnabled: 1,
                //             isMustUpload: 0,
                //             isNil: null,
                //             isPass: null,
                //             offline: 0,
                //             parentId: null,
                //             reserved1: null,
                //             reserved2: "SENCE_INSTALL_0_0_0_1",
                //             reserved3: null,
                //             sort: 0,
                //             templateAttachs: [],
                //             templatePath: null,
                //             templateType: null,
                //             typeCode: "EQM_INSTALL_PROCESS_JOB",
                //             typeId: "EQM_INSTALL_PROCESS_JOB",
                //             typeName: "安装过程/安装单位/作业情况",
                //             uploadFrom: "1",
                //             uploadTime:null,
                //             uploaderId:null,
                //             uploaderName: null,
                //         }
                //     ]
                // },
            ],
            groupList:[
                // {
                //     name:'第一步',
                //     code:1,
                //     insStatus:0,
                //     conStatus:0,
                //     fileList:[
                //         {
                //             isConfirm:true,
                //             allowMark: 1,
                //             allowNone: 0,
                //             attachReserved1: null,
                //             attachReserved2: null,
                //             attachReserved3: null,
                //             attachmentId: null,
                //             attachments: [],
                //             bizType: "SENCE_INSTALL_0_0_0_1",
                //             children: [],
                //             craneType: null,
                //             customDesc: "辅助汽车吊检测报告",
                //             customName: "辅助汽车吊检测报告",
                //             dataKey: null,
                //             fileName: null,
                //             fileSizeLimit: null,
                //             fileType: null,
                //             fileTypes: null,
                //             id: "0fdb3db6-139f-4839-b50d-fbc6b7c112f9",
                //             isConfirm: null,
                //             isEnabled: 1,
                //             isMustUpload: 0,
                //             isNil: null,
                //             isPass: null,
                //             offline: 0,
                //             parentId: null,
                //             reserved1: null,
                //             reserved2: "SENCE_INSTALL_0_0_0_1",
                //             reserved3: null,
                //             sort: 0,
                //             templateAttachs: [],
                //             templatePath: null,
                //             templateType: null,
                //             typeCode: "EQM_INSTALL_PROCESS_JOB",
                //             typeId: "EQM_INSTALL_PROCESS_JOB",
                //             typeName: "安装过程/安装单位/作业情况",
                //             uploadFrom: "1",
                //             uploadTime:null,
                //             uploaderId:null,
                //             uploaderName: null,
                //         }
                //     ]
                // },
                // {
                //     name:'第二步',
                //     code:2,
                //     insStatus:0,
                //     conStatus:0,
                //     fileList:[
                //         {
                //             isConfirm:true,
                //             allowMark: 1,
                //             allowNone: 0,
                //             attachReserved1: null,
                //             attachReserved2: null,
                //             attachReserved3: null,
                //             attachmentId: null,
                //             attachments: [],
                //             bizType: "SENCE_INSTALL_0_0_0_1",
                //             children: [],
                //             craneType: null,
                //             customDesc: "辅助汽车吊检测报告",
                //             customName: "辅助汽车吊检测报告",
                //             dataKey: null,
                //             fileName: null,
                //             fileSizeLimit: null,
                //             fileType: null,
                //             fileTypes: null,
                //             id: "0fdb3db6-139f-4839-b50d-fbc6b7c112f9",
                //             isConfirm: null,
                //             isEnabled: 1,
                //             isMustUpload: 0,
                //             isNil: null,
                //             isPass: null,
                //             offline: 0,
                //             parentId: null,
                //             reserved1: null,
                //             reserved2: "SENCE_INSTALL_0_0_0_1",
                //             reserved3: null,
                //             sort: 0,
                //             templateAttachs: [],
                //             templatePath: null,
                //             templateType: null,
                //             typeCode: "EQM_INSTALL_PROCESS_JOB",
                //             typeId: "EQM_INSTALL_PROCESS_JOB",
                //             typeName: "安装过程/安装单位/作业情况",
                //             uploadFrom: "1",
                //             uploadTime:null,
                //             uploaderId:null,
                //             uploaderName: null,
                //         }
                //     ]
                // },
            ],
            active:0,
            chineseIndex:['一','二','三','四','五','六','七','八','九','十','十一','十二','十三','十四','十五','十六','十七','十八','十九','二十'],
            pstatus:6,
        }
    },
    created() {
        this.unwacth = this.$watch(
            'dataKey',
            function (val) {
                if (val) {
                    this.getFileList()
                }
            },
            {
                deep: true,
                immediate: true,
            }
        )
    },
    methods: {
        handleOverTime(row){
            return
            this.$f7.preloader.show();
            this.$framework.util
            .getPromise(`/app/workflow/getWorkflowArgs`, { formId: row.id })
            .then(res => {
                if (!res.pageAction || !res.assigneeId) {
                this.$f7.preloader.hide();
                return;
                }
                let url=res.mobileFormUrl
                const params = {
                    pageAction: res.pageAction,
                    assigneeId: res.assigneeId,
                    notifyId:this.notifyId,
                    action:res.pageAction=='edit'?'processEdit':'processView',
                    version:res.version,
                    formId:row.id,
                };

                if (res.pageAction === 'view') {
                Object.assign(params, { historyTaskId: res.historyTaskId })
                } else {
                Object.assign(params, { taskId: res.taskId })
                }
                let paramStr = [];
                for (let key in params) {
                paramStr.push(`${key}=${params[key]}`);
                }
                paramStr = paramStr.join("&");
                this.$f7.view.current.router.navigate(url+`?${paramStr}`);
            })
            .catch(err => {
                this.$f7.preloader.hide();
            })
            .finally(() => {});
        },
        actionsGroup(item){
            if(this.isOffline){
                return [1,2]
            }else{
                return item.uploadFrom?item.uploadFrom.split(','):this.actionsOneGroup
            }
        },
        // 校验
        checkGroupFile(pindex){
            return new Promise((resolve, reject) => {
                try {
                    let fileList=this.sectionList[pindex].fileList
                    let count=0
                    let getCount=0
                    fileList.forEach((item,index)=>{
                        if(Array.isArray(this.$refs[`${this.listName}${index + 1}${pindex}`])){
                            getCount=this.$refs[`${this.listName}${index + 1}${pindex}`][0].getUploadedCount()
                        }else{
                            getCount=this.$refs[`${this.listName}${index + 1}${pindex}`].getUploadedCount()
                        }
                        // 必填项 且 附件数量>0
                        if (item.isMustUpload && getCount > 0) {
                            count++
                        }else if(item.isNil&&item.isMustUpload){ // 如果是必填项，但勾选了无此项，也算作上传的意思
                            count++
                        }
                    })
                    resolve(count>0?true:false)
                } catch (error) {
                    console.log(error)
                    reject(false)
                }
            })
        },
        // 双确认
        async handleConfirm(item,type,index,field){
            let overtimeEntity=item.confirmInfo.overtimeEntity
            // 确认双确认附件项必填
            let flag=await this.checkGroupFile(index)
            if(!flag) return this.$toast('请上传必填附件项后再确认！')
            // 未确认的项才允许确认
            if(item.confirmInfo[field]==0){
                this.$f7.dialog.confirm(`确认符合安全规范？`, r => {
                    if (r) {
                        this.$f7.preloader.show();
                        this.$f7.request.postJSON(
                            '/equipment/eqmCase/processConfirm', 
                            {confirmId:item.confirmInfo.confirmId,type}, 
                            (r) => {
                                this.$f7.preloader.hide();
                                if(r.success){
                                    // 如果是安装单位确认，则需要重新获取整个文件列表
                                    // 因为qm-file-upload传了默认附件值，而我们的附件值并不符合组件的需求，所以重新渲染
                                    if(field=='insStatus'){
                                        this.getFileList()
                                    }else{ // 否则施工单位直接替换双确认结果即可
                                        // 赋值到confirmInfo
                                        item.confirmInfo=r.parameters.processConfirm
                                        item.confirmInfo.overtimeEntity=overtimeEntity
                                        // 替换当前项的confirmInfo
                                        this.sectionList.splice(index,1,item)
                                        if(this.isOffline) return 
                                        // 校验双确认两个单位是否确认完毕，确认完毕自动加载下一步骤
                                        let flagIns=this.sectionList[index].confirmInfo.insStatus==1
                                        let flagCon=this.sectionList[index].confirmInfo.conStatus==1
                                        // 加定时器原因，双确认完毕马上加载下一步的效果太快了，没看清楚确认结果，所以加一个一秒的延时器
                                        let timer=setTimeout(() => {
                                            // 两个单位确认完毕后，校验是否已经加载全部，如果加载完全部双确认项，则不再加载下一步
                                            if(flagIns&&flagCon&&this.sectionList.length<this.groupList.length){
                                                this.sectionList.push(this.groupList[this.sectionList.length])
                                                this.active++
                                            }
                                            this.$forceUpdate()
                                            // 清除定时器
                                            if(timer) clearTimeout(timer)
                                        }, 1000);
                                    }
                                    
                                }else{
                                    this.$toast(r.message||`${type==0?'取消':'确认'}失败`)
                                }
                            }, (r) => {
                                this.$f7.preloader.hide();
                            }
                        );
                    }
                });
            }
        },
        // 
        noPermission(type){
            if(type == 'install'){
                this.$f7.dialog.alert("请用技术负责人账号操作");
            }else if(type == 'construction'){
                this.$f7.dialog.alert("请用设备管理人操作");
            }
        },
        // 获取附件信息
        getFileList() {
            // 取消监听
            if (this.unwacth) this.unwacth()
            this.$f7.preloader.show();
            this.$f7.request.post(
                '/equipment/eqmCase/confirmListUpload',
                {
                    typeCode: this.typeCode,
                    dataKey: this.dataKey,
                    attachCraneType: this.attachCraneType,
                },
                (r) => {
                    r = JSON.parse(r)
                    this.sectionList=[]
                    if (r?.success && r.parameters.groupList) {
                        this.groupList = r.parameters.groupList
                        this.active=r.parameters.currentGroupNum
                        this.isOffline=r.parameters.offline
                        // 如果当前激活项是0（特殊值）则代表已经做完双确认，则直接groupList=sectionList
                        if(this.active==0||this.isOffline){
                           this.sectionList= this.groupList
                        }else{ // 否则根据active的值去push groupList的值
                            for (let i = 0; i < this.active; i++) {
                                this.sectionList.push(this.groupList[i])
                            }
                        }
                        this.$f7.preloader.hide();
                        return
                    }
                    this.$f7.preloader.hide();
                    this.sectionList = []
                    this.$framework.$f7.dialog.toast('获取文件失败')
                },
                (e)=>{
                    this.$f7.preloader.hide();
                    console.log(e);
                    this.$toast('获取信息失败，请联系管理员')
                }
            )
        },
        // 无此项 处理函数
        checkItem(item,index) {
            this.$util.getPromise(
                `/admin/attachmentFormDetail/saveAllowNone`, 
                { caseId:this.dataKey,dicId:item.id,type:item.isNil?1:0 }
            )
            .then(r => {
                if(!r.success){
                    this.$toast('勾选失败！')
                    item.isNil=false
                }
            })
        },
        // 上传成功回调函数
        fileOnSuccess(){
            this.getNum()
        },
        // 删除成功回调函数
        deleteFileAfter(){
            this.getNum()
        },
        // 获取整体count值(例如：0/0)
        getCounts(){
            return new Promise((resolve, reject) => {
                try {
                    let count=0
                    let getCount=0
                    let concatList=[]
                    this.groupList.forEach(item=>{
                        concatList.push(...item.fileList)
                    })
                    this.sectionList.forEach((element, idx) => {
                        element.fileList.forEach((item,index)=>{
                            if(Array.isArray(this.$refs[`${this.listName}${index + 1}${idx}`])){
                                getCount=this.$refs[`${this.listName}${index + 1}${idx}`][0].getUploadedCount()
                            }else{
                                getCount=this.$refs[`${this.listName}${index + 1}${idx}`].getUploadedCount()
                            }
                            if (getCount > 0 ) {
                                count++
                            }
                        })
                    })
                    resolve (`${count}/${concatList.length}`)
                } catch (error) {
                    resolve('0/0')
                }
            })
        },
        getNum(){
            this.$nextTick(async ()=>{
                this.count=await this.getCounts()
                this.$emit('getCount',this.count)
            })
        },
    },
    watch:{
        groupList:{
            handler(val){
                this.getNum()
            },
            immediate:true,
            deep:true,
        }
    }
}
</script>

<style lang="less" scoped>
@import url('../../../../assets/css/commonPage.less');

@{deep}.accordion .accordion-item > .item-link > .item-content {
    padding-left: 16px !important;
}

.picList .infoList {
    margin-top: 10px;
}
span.tag{
    padding: 2px 6px;
}
li {
    &:first-child .content-box {
        margin-top: 0;
    }

    .content-box {
        background: #fff;
        margin-bottom: 0;
        align-items: flex-start;
        box-shadow: none;
        padding: 10px 0;
    }

    .index-box {
        padding: 2px 8px;
        background: rgba(51, 133, 255, 0.1);
        border-radius: 1px;
        font-size: 13px;
        color: #1990ff;
    }

    .right-box {
        margin-left: 10px;
        font-size: 14px;
        color: #333;
        .code{
            display: flex;
            justify-content: space-between;
            align-items: center;
            section{
                display: flex;
                span{
                    flex-shrink: 0;
                    height: 16px;
                    line-height: 16px;
                }
            }
        }
    }

    .checks-box {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;

        .code {
            width: 72%;
        }
    }
    
}
.confirm-ul{
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    .confirm-li{
        width: 45%;
        position: relative;
        background: #F5F8FF;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #8995AC;
        font-size: 14px;
        padding: 15px 5px;
        min-height: 103px;
        img{
            position: absolute;
            right: -10px;
            top: -12px;
            width: 37px;
            height: 35px;
            z-index: 11;
        }
        span:nth-child(1){
            color: #333333;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
            text-align: center;
            &.toSure{
            font-weight: 300;
            color: #909DB6;
            }
        }
    }
}
/deep/.pic_upload {
    padding: 10px 0 !important;
}
.right-box-bottom{
    display: flex;
    
}
.noUpload{
    background: #f7f8fa;
    color: #b7c2d9;
    border: 1px solid #b7c2d9;
    border-radius: 6px;
    border-bottom-left-radius: 0;
    padding: 2px 5px;
    font-size: 12px;
    margin-left: 5px;
}
/deep/ .van-notice-bar{
    margin: 15px 12px 0;
    padding: 8px 10px;
    .van-notice-bar__content{
        font-size: 12px;
        font-weight: 400;
    }
}
</style>
